package com.woniuxy.gateway.filter;

import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static com.woniuxy.common.constant.CommunityConstant.UserConstant.*;

/**
 * @author     ：hy zhu
 * @date       ：Created in 2025/5/29 11:51
 * @description：TODO
 * @modified By：
 * @version: 1, 0
 */
@Slf4j
@Order(1)
@Component
public class LoginFilter implements GlobalFilter {


    @Autowired
    private ReactiveStringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //  白名单
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();

        return redisTemplate.opsForHash().hasKey(WHITE_LIST, path).flatMap(b -> {
            if (b) {
                return chain.filter(exchange);
            } else {
                //认证
                // 1、获取token
                String token = request.getHeaders().getFirst(TOKEN);
                // 2、校验token
                try {
                    boolean verify = JWTUtil.verify(token, WONIU.getBytes());
                    if (!verify) {
                        return noLogin(exchange);
                    }
                } catch (Exception e) {
                    return noLogin(exchange);
                }
                // 放行
                return chain.filter(exchange);
            }
        });


    }

    private static Mono<Void> noLogin(ServerWebExchange exchange) {
        //从上到下级别越来越高
//        log.trace("");
//        log.debug("");
//        log.info("");
//        log.warn("");
        log.error("认证失败");
        // 3、校验失败，返回401
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }
}
